//SingletonKeyGenerator.java
package singletonAndMultiton;

import java.util.HashMap;

/**
 *@author:youtubezou
 *@version:2012-7-14
 */
public class SingletonKeyGenerator {
	/*Note: there is only one SingletonKeyGenerator object exists*/
	private static SingletonKeyGenerator keyGen = new SingletonKeyGenerator();
	
	/*Note: collection holds the KeyInfo objects, not SingletonKeyGenerator object*/
	private static HashMap<String, KeyInfo> keyLists = new HashMap<String, KeyInfo>(10);
	private static final int POOL_SIZE = 20;
	
	private SingletonKeyGenerator(){
	}
	
	public static SingletonKeyGenerator getInstance(){
		return keyGen;
	}
	
	public synchronized int getNextKey(String name){	
		if (keyLists.containsKey(name) == false){
			keyLists.put(name, new KeyInfo(POOL_SIZE, name));		
		}
		
		return keyLists.get(name).getNextKey();
	}
	
	
	public static void main(String[] args) {
		SingletonKeyGenerator key = SingletonKeyGenerator.getInstance();
		
		System.out.println("SingletonKeyGenerator Test");
		for (int i = 0; i < 30; i++){
			System.out.println(key.getNextKey("US"));
		}
	}

}
